package vip.xiaonuo.smzq.modular.hisi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.github.yulichang.wrapper.interfaces.MFunction;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Point;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.core.tools.excel.ExcelExporter;
import vip.xiaonuo.smzq.core.tools.excel.ExcelToReadUtil;
import vip.xiaonuo.smzq.core.utils.TransFormUtil;
import vip.xiaonuo.smzq.modular.deom.ToolData;
import vip.xiaonuo.smzq.modular.deom.TypeProcessing;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb01Zh;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb06Kc;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb08Xzqh;
import vip.xiaonuo.smzq.modular.dictionary.entity.vo.DirTree;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb01ZhMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb06KcMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb08XzqhMapper;
import vip.xiaonuo.smzq.modular.hisi.entity.AsyncHead;
import vip.xiaonuo.smzq.modular.hisi.entity.HisiKs;
import vip.xiaonuo.smzq.modular.hisi.entity.KsZyclhz;
import vip.xiaonuo.smzq.modular.hisi.entity.Kshz;
import vip.xiaonuo.smzq.modular.hisi.entity.param.ZyclBhlParam;
import vip.xiaonuo.smzq.modular.hisi.entity.vo.*;
import vip.xiaonuo.smzq.modular.hisi.mapper.HisiKsMapper;
import vip.xiaonuo.smzq.modular.hisi.service.IHisiKsService;
import vip.xiaonuo.smzq.modular.hisi.service.IKshzService;
import vip.xiaonuo.smzq.modular.jsc.entity.vo.Dcexcelkccb;
import vip.xiaonuo.smzq.modular.jsc.entity.vo.Dykcfb;
import vip.xiaonuo.smzq.modular.jsc.entity.vo.Kcfb;
import vip.xiaonuo.smzq.modular.kcl.entity.Bg;
import vip.xiaonuo.smzq.modular.kcl.entity.Ks;
import vip.xiaonuo.smzq.modular.kcl.entity.Zb;
import vip.xiaonuo.smzq.modular.kcl.entity.Zycl;
import vip.xiaonuo.smzq.modular.kcl.mapper.BgMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.KsMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.ZbMapper;
import vip.xiaonuo.smzq.modular.nbfb.entity.param.NbfbSixParam;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbSixVo;
import vip.xiaonuo.smzq.modular.nbfb.mapper.ZyclSixMapper;
import vip.xiaonuo.smzq.modular.nbfb.service.impl.NbfbSixServiceImpl;
import vip.xiaonuo.smzq.modular.user.entity.Role;
import vip.xiaonuo.smzq.modular.user.entity.User;
import vip.xiaonuo.smzq.modular.user.mapper.RoleMapper;
import vip.xiaonuo.smzq.modular.user.mapper.UserMapper;
import vip.xiaonuo.sys.modular.role.enums.SysRoleEnum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 矿山信息 服务实现类
 *
 * @author eomer
 * @since 2024-02-22
 */
@Service
public class HisiKsServiceImpl extends ServiceImpl<HisiKsMapper, HisiKs> implements IHisiKsService {

    @Resource
    private HisiKsMapper hisiKsMapper;

    @Resource
    private Cb08XzqhMapper cb08XzqhMapper;//行政区划
    @Resource
    private UserMapper userMapper;//用户
    @Resource
    private Cb06KcMapper cb06KcMapper; //矿产

    @Resource
    private KsMapper ksMapper;//矿山信息

    @Resource
    private BgMapper bgMapper; //报告
    @Resource
    private ZbMapper zbMapper; //坐标

    @Resource
    private Cb01ZhMapper cb01ZhMapper; //字典综合01
    @Resource
    TransFormUtil transFormUtil; //坐标相关工具类

    //矿山综合服务
    @Resource
    private IKshzService iKshzService;
    //角色
    @Resource
    private RoleMapper roleMapper;

    //年报附表6
    @Resource
    private ZyclSixMapper zyclSixMapper;

    @Resource
    private CommonCacheOperator commonCacheOperator;//缓冲机制


    @Override
    public Page<HisiKs> page(HisiKs hisiKs) {
        QueryWrapper<HisiKs> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public Page<Ksxicx> pageHisiKs(CxtjMhtj cxtjMhtj) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        Page<HisiKs> page = new Page<>();
        Page<Ksxicx> returnPage = new Page<>();
        page.setCurrent(cxtjMhtj.getCurrent());
        page.setSize(cxtjMhtj.getSize());
        QueryWrapper<HisiKs> queryWrapper = new QueryWrapper<>();
        //拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            queryWrapper.eq("nd", cxtjMhtj.getNd());
        }
        //拼接矿山名称信息
        if (cxtjMhtj.getKsmc() != null) {
            queryWrapper.like("ksmc", cxtjMhtj.getKsmc());
        }
        //拼接矿山编号信息
        if (cxtjMhtj.getKsbh() != null) {
            queryWrapper.like("ksbh", cxtjMhtj.getKsbh());
        }
        //拼接矿区编号信息
        if (cxtjMhtj.getKqbh() != null) {
            queryWrapper.like("kqbh", cxtjMhtj.getKqbh());
        }
        //拼接矿区名称
        if (cxtjMhtj.getKqmc() != null) {
            queryWrapper.like("kqmc", cxtjMhtj.getKqmc());
        }
        //拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            queryWrapper.eq("kcdm", String.valueOf(cxtjMhtj.getKzbh()));
        }
        //登记分类编号
        if (cxtjMhtj.getDjflbh() != null) {
            queryWrapper.eq("djflbh", String.valueOf(cxtjMhtj.getDjflbh()));
        }
        //矿业权人
        if (cxtjMhtj.getKyqr() != null) {
            queryWrapper.eq("kyqr", cxtjMhtj.getKyqr());
        }
        //规模
        if (cxtjMhtj.getGm() != null) {
            queryWrapper.eq("gm", cxtjMhtj.getGm());
        }
        //利用情况
        if (cxtjMhtj.getSfly() != null) {
            queryWrapper.eq("sfly", cxtjMhtj.getSfly());
        }
        //有效期模糊查询
        if (cxtjMhtj.getYxq() != null) {
            queryWrapper.like("yxq", cxtjMhtj.getYxq());
        }
        //行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .collect(Collectors.toList());

            queryWrapper.in("xzqdm", xzqhList);
        } else {
            //行政区代码
            String xzqh = "";
            if (user.getOrgId() == null) {
                if (user.getOrgId().equals("-1")) {
                    xzqh = "130000";
                } else {
                    xzqh = user.getOrgId();
                }
            } else {
                xzqh = "130000";
            }

            xzqh = xzqh.replaceAll("0+$", "");
            queryWrapper.like("xzqdm", xzqh);
        }
        //许可证号
        if (cxtjMhtj.getXkzh() != null) {
            queryWrapper.eq("xkzh", cxtjMhtj.getXkzh());
        }
        //勘察程度
        if (cxtjMhtj.getKccd() != null) {
            queryWrapper.eq("kcjdm", cxtjMhtj.getKccd());
        }
        //开采情况（0未开采，1开采）
        if (cxtjMhtj.getKcqk() != null) {
            queryWrapper.eq("kcqk", cxtjMhtj.getKcqk());
        }
        //是否出界（0未出界，1出界）
        if (cxtjMhtj.getSfcj() != null) {
            queryWrapper.eq("sfcj", cxtjMhtj.getSfcj());
        }
        //矿产组合码
        if (cxtjMhtj.getKczh() != null) {
            queryWrapper.eq("kczhm", Integer.valueOf(cxtjMhtj.getKczh()));
        }

        queryWrapper.orderByDesc("nd");
        queryWrapper.orderByAsc("kqbh");
        page = hisiKsMapper.selectPage(page, queryWrapper);

        List<HisiKs> hisiKs = page.getRecords();
        List<Ksxicx> ksxicxs = new ArrayList<>();

        for (HisiKs hisiKs1 : hisiKs) {
            Ksxicx ksxicx = new Ksxicx();
            BeanUtil.copyProperties(hisiKs1, ksxicx);

            QueryWrapper<Cb08Xzqh> xianWrapper = new QueryWrapper<>();
            xianWrapper.eq("dm", Integer.parseInt(hisiKs1.getXzqdm()));
            Cb08Xzqh xian = cb08XzqhMapper.selectOne(xianWrapper);

            QueryWrapper<Cb08Xzqh> shiWrapper = new QueryWrapper<>();
            shiWrapper.eq("dm", xian.getFdm());
            Cb08Xzqh shi = cb08XzqhMapper.selectOne(shiWrapper);

            QueryWrapper<Cb08Xzqh> shengWrapper = new QueryWrapper<>();
            shengWrapper.eq("dm", shi.getFdm());
            Cb08Xzqh sheng = cb08XzqhMapper.selectOne(shengWrapper);
            ksxicx.setXzqhmc(sheng.getMc() + ">" + shi.getMc() + ">" + xian.getMc());
            ksxicxs.add(ksxicx);

        }

        returnPage.setCurrent(page.getCurrent());
        returnPage.setSize(page.getSize());
        returnPage.setRecords(ksxicxs);
        returnPage.setTotal(page.getTotal());

        return returnPage;

    }


    /**
     * 矿山信息数量查询
     * 矿产地信息数量查询
     */
    @Override
    public Cxtjsljs getCxtjsljs(CxtjMhtj cxtjMhtj) {
        Cxtjsljs cxtjsljs = new Cxtjsljs();
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        if (cxtjMhtj.getKzbh() == null) {
            return cxtjsljs;
        }

        String sql = "where";
        //拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            sql += " nd=" + cxtjMhtj.getNd() + " and";

        }
        //拼接矿山名称信息
        if (cxtjMhtj.getKsmc() != null) {
            sql += " ksmc like '%" + cxtjMhtj.getKsmc() + "%' and";

        }

        //拼接矿区编号信息
        if (cxtjMhtj.getKqbh() != null) {
            sql += " kqbh like '%" + cxtjMhtj.getKqbh() + "%' and";
        }

        //拼接矿区名称
        if (cxtjMhtj.getKqmc() != null) {
            sql += " kqmc like '%" + cxtjMhtj.getKqmc() + "%' and";
        }

        //拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            sql += " kcdm='" + cxtjMhtj.getKzbh() + "' and";

        }

        //登记分类编号
        if (cxtjMhtj.getDjflbh() != null) {
            sql += " djflbh='" + cxtjMhtj.getDjflbh() + "' and";
        }
//矿业权人
        if (cxtjMhtj.getKyqr() != null) {
            sql += " kyqr='" + cxtjMhtj.getKyqr() + "' and";
        }
        //规模
        if (cxtjMhtj.getGm() != null) {
            sql += " gm='" + cxtjMhtj.getGm() + "' and";
        }
        //利用情况
        if (cxtjMhtj.getSfly() != null) {
            sql += " sfly=" + cxtjMhtj.getSfly() + " and";
        }
        //有效期模糊查询
        if (cxtjMhtj.getYxq() != null) {
            sql += " yxq like '%" + cxtjMhtj.getYxq() + "%' and";
        }
//行政区代码级联多选
        //行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .collect(Collectors.toList());

            String xzqsql = "(";

            for (String xzqh : xzqhList) {
                xzqsql += "'" + xzqh + "',";
            }
            xzqsql = xzqsql.substring(0, xzqsql.length() - 1) + ")";
            sql += " xzqdm in " + xzqsql + " and";
        } else {
            //行政区代码
            String xzqh = "";
            if (user.getOrgId() == null) {
                if (user.getOrgId().equals("-1")) {
                    xzqh = "130000";
                } else {
                    xzqh = user.getOrgId();
                }
            } else {
                xzqh = "130000";
            }

            xzqh = xzqh.replaceAll("0+$", "");
            sql += " xzqdm like '" + xzqh + "%' and";
        }
        //许可证号
        if (cxtjMhtj.getXkzh() != null) {
            sql += " xkzh='" + cxtjMhtj.getXkzh() + "' and";
        }
        //勘察程度
        if (cxtjMhtj.getKccd() != null) {
            sql += " kcjdm=" + cxtjMhtj.getKccd() + " and";
        }

        //开采情况（0未开采，1开采）
        if (cxtjMhtj.getKcqk() != null) {
            sql += " kcqk=" + cxtjMhtj.getKcqk() + " and";
        }

        //是否出界（0未出界，1出界）
        if (cxtjMhtj.getSfcj() != null) {
            sql += " sfcj=" + cxtjMhtj.getSfcj() + " and";
        }
        //矿产组合码
        if (cxtjMhtj.getKczh() != null) {
            sql += " kczhm=" + cxtjMhtj.getKczh() + " and";

        }
        sql = sql.substring(0, sql.length() - 4);
        cxtjsljs = hisiKsMapper.getCxtslis(sql);


        return cxtjsljs;
    }


    /**
     * 资源储量查询
     */
    @Override
    public ZyclCount getZyclCount(CxtjMhtj cxtjMhtj) {
        ZyclCount zyclCount = new ZyclCount();
        cxtjMhtj.setCurrent(1);
        cxtjMhtj.setSize(999999999);
        if (cxtjMhtj.getKzbh() == null) {
            return zyclCount;
        }
        Page<Zyclcx> page = pageZyclcx(cxtjMhtj);
        List<Zyclcx> zyclcxList = page.getRecords();
        // "证实量")
        Double zsl = 0.0;
        // "可信量")
        Double kxl = 0.0;
        // "证实可信合计")
        double zskxhjl = 0.0;
        // "探明量")
        Double tml = 0.0;
        // "控制量")
        Double kzl = 0.0;
        // "推断量")
        Double tdl = 0.0;
        // "探明，控制，推断合计量")
        Double tmkztdl = 0.0;

        for (Zyclcx zyclcx : zyclcxList) {
            zsl += zyclcx.getZsl();
            kxl += zyclcx.getKxl();
            zskxhjl += zyclcx.getZskxhjl();
            tml += zyclcx.getTml();
            kzl += zyclcx.getKzl();
            tdl += zyclcx.getTdl();
            tmkztdl += zyclcx.getTmkztdl();
        }
        DecimalFormat df = new DecimalFormat("#.##");

        zyclCount.setZj(zyclcxList.size());
        zyclCount.setZsl(Double.parseDouble(df.format(zsl)));
        zyclCount.setKxl(Double.parseDouble(df.format(kxl)));
        zyclCount.setZskxhjl(Double.parseDouble(df.format(zskxhjl)));
        zyclCount.setTml(Double.parseDouble(df.format(tml)));
        zyclCount.setKzl(Double.parseDouble(df.format(kzl)));
        zyclCount.setTdl(Double.parseDouble(df.format(tdl)));
        zyclCount.setTmkztdl(Double.parseDouble(df.format(tmkztdl)));
        return zyclCount;
    }

    /**
     * 资源储量总数量查询
     */
    @Override
    public ZyclCount selectZyclCount(CxtjMhtj cxtjMhtj) {

        ZyclCount zyclCount = new ZyclCount();

//        QueryWrapper<Map> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like(StrUtil.isNotBlank(cxtjMhtj.getKqbh()), "kqbh", cxtjMhtj.getKqbh());
//        queryWrapper.like(StrUtil.isNotBlank(cxtjMhtj.getKqmc()), "kqmc", cxtjMhtj.getKqmc());
//        queryWrapper.eq(cxtjMhtj.getNd() != null, "nd", cxtjMhtj.getNd());
//        queryWrapper.eq(cxtjMhtj.getKzbh() != null, "kcdm", cxtjMhtj.getKzbh());
//        //行政区代码级联多选
//        if (StrUtil.isNotBlank(cxtjMhtj.getXzqh())) {
//            queryWrapper.in("xzqdm", Arrays.asList(cxtjMhtj.getXzqh().split(",")));
//        } else {
//            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
//            User user = userMapper.selectById(saBaseLoginUser.getId());
//            String xzqh = user.getOrgId();
//            if (user.getOrgId().equals("0") || user.getOrgId().equals("-1")) {
//                xzqh = "130000";
//            }
//            xzqh = xzqh.replaceAll("0+$", "");
//            queryWrapper.like("xzqdm", xzqh);
//        }

        String sql = "";
        if (cxtjMhtj.getKqbh() != null && cxtjMhtj.getKqbh().length() > 0) {
            sql += " and kqbh like'%" + cxtjMhtj.getKqbh() + "%'";
        }
        if (cxtjMhtj.getKqmc() != null && cxtjMhtj.getKqmc().length() > 0) {
            sql += " and kqmc like'%" + cxtjMhtj.getKqmc() + "%'";
        }
        if (cxtjMhtj.getNd() != null && cxtjMhtj.getNd() > 0) {
            sql += " and nd=" + cxtjMhtj.getNd();
        }
        if (cxtjMhtj.getKzbh() != null && !cxtjMhtj.getKzbh().equals("")) {
            sql += " and kcdm='" + cxtjMhtj.getKzbh() + "'";
        }
        //行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null && cxtjMhtj.getXzqh().length() > 0) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .collect(Collectors.toList());
            String xzqhSql = "(";
            for (String xzqh : xzqhList) {
                xzqhSql += "'" + xzqh + "',";
            }
            xzqhSql = xzqhSql.substring(0, xzqhSql.length() - 1) + ")";

            sql += " and xzqdm in" + xzqhSql;
        } else {
            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
            User user = userMapper.selectById(saBaseLoginUser.getId());
            String xzqh = user.getOrgId();
            if (user.getOrgId().equals("0") || user.getOrgId().equals("-1")) {
                xzqh = "130000";
            }
            xzqh = xzqh.replaceAll("0+$", "");
            sql += " and xzqdm like'%" + xzqh + "%'";
        }

        List<ZyclCount> list = hisiKsMapper.selectZyclCount2(sql);
        if (CollectionUtil.isNotEmpty(list)) {
            zyclCount = list.get(0);
        }

        List<Map> zjList = hisiKsMapper.selectZyclZj(sql);
        if (CollectionUtil.isNotEmpty(zjList)) {
            zyclCount.setZj(zjList.size());
        }

        return zyclCount;
    }

    @Override
    public void exportZyclBhl(String nd) {
        String[] numbersAsStrArray = nd.replace("，", ",").split(",");
        // 使用流(Stream)转换并收集到List<Integer>
        List<Integer> ndList = Arrays.stream(numbersAsStrArray)
                .map(Integer::parseInt) // 将每个字符串转换为Integer
                .collect(Collectors.toList()); // 收集到List中
        List<Map<String, Object>> mapList = hisiKsMapper.getzyclBhl(ndList);
        Map<String, String> titleMap = new HashMap<>();
        if (!mapList.isEmpty()) { // 确保列表不为空
            Map<String, Object> firstMap = mapList.get(0);
            titleMap = getHeader(firstMap);
        }
        System.out.println(titleMap);
        System.out.println(mapList);
    }

    /**
     * 获取动态表头
     *
     * @param data
     * @author Kevin
     * @since 2024/7/5 10:19
     */
    public Map<String, String> getHeader(Map<String, Object> data) {
        Map<String, String> titleMap = new HashMap<>();
        List<String> keysAsList = new ArrayList<>(data.keySet());
        for (String key : keysAsList) {
            switch (key) {
                case "kcmc":
                    titleMap.put(key, "矿产名称");
                    break;
                case "tjdx":
                    titleMap.put(key, "统计对象");
                    break;
                case "jsldw":
                    titleMap.put(key, "金属量单位");
                    break;
                case "ksldw":
                    titleMap.put(key, "矿石量单位");
                    break;
                case "smc":
                    titleMap.put(key, "市名称");
                    break;
                case "xmc":
                    titleMap.put(key, "县名称");
                    break;
            }
            if (key.contains("nmbyl")) {
                String str = key.replace("nmbyl", "年末保有量");
                titleMap.put(key, str);
            }
            if (key.contains("ncbyl")) {
                String str = key.replace("ncbyl", "年初保有量");
                titleMap.put(key, str);
            }
            if (key.contains("bhl")) {
                String str = key.replace("bhl", "变化量");
                titleMap.put(key, str);
            }
        }
        return titleMap;
    }

    public List<AsyncHead> getAsyncHead(String[] yearsArray) {
        List<AsyncHead> asyncHeadList = new ArrayList<>();

        asyncHeadList.add(new AsyncHead("smc", "市名称"));
        asyncHeadList.add(new AsyncHead("xmc", "县名称"));
        asyncHeadList.add(new AsyncHead("kcmc", "矿产名称"));
        asyncHeadList.add(new AsyncHead("jsdxmc", "统计对象名称"));
//        asyncHeadList.add(new AsyncHead("tjdx", "统计对象"));
        asyncHeadList.add(new AsyncHead("jsldw", "金属量单位"));
        asyncHeadList.add(new AsyncHead("ksldw", "矿石量单位"));


        Arrays.sort(yearsArray, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return Integer.compare(Integer.parseInt(s2), Integer.parseInt(s1)); // 倒序比较
            }
        });

        Arrays.sort(yearsArray);
        for (String year : yearsArray) {
            asyncHeadList.add(new AsyncHead("ncbyl" + year, year + "年初保有量"));
            asyncHeadList.add(new AsyncHead("bhl" + year, year + "变化量"));
            asyncHeadList.add(new AsyncHead("nmbyl" + year, year + "年末保有量"));
        }

        return asyncHeadList;
    }

    /**
     * 多年年初年末保有量的变化量-分页查询
     */
    @Override
    public Map<String, Object> pageZyclBhl(ZyclBhlParam param) {

        Map<String, Object> result = new HashMap<>();
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        //分页查询数据
        Page<Map<String, Object>> page = new Page<>(param.getCurrent(), param.getSize());
        String[] numbersAsStrArray = param.getNd().replace("，", ",").split(",");
        //参数转换为List<Integer>
        List<Integer> ndList = Arrays.stream(numbersAsStrArray)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        //矿区编号
        String kqbh = "";
        //行政区代码
        List<Integer> xzqhList = new ArrayList<>();
        //矿产代码
        Integer kcdm = 0;
        //统计对象
        Integer tjdx = 0;
        //矿区名称
        String kqmc = "";
        if (param.getKcdm() != null) {

            List<Integer> kzbhList = TypeProcessing.strToList(param.getKcdm());
            if (kzbhList != null && kzbhList.size() == 3) {
                if (kzbhList.get(0) == 2) {
                    kcdm = kzbhList.get(1);
                } else if (kzbhList.get(0) == 3) {
                    kcdm = kzbhList.get(1);
                    tjdx = kzbhList.get(2);
                }
            }
//            kcdm = param.getKcdm();
        }
        if (param.getKqbh() != null) {
            kqbh = param.getKqbh();
        }
        if (param.getXzqh() != null) {
            //参数转换为List<Integer>
            xzqhList = Arrays.stream(param.getXzqh().replace("，", ",").split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        } else {
            //根据用户权限获取行政区信息
            xzqhList = getXzqhbh();
        }
        if (param.getKqmc() != null) {
            kqmc = param.getKqmc();
        }

        List<Map<String, Object>> mapList = hisiKsMapper.getzyclBhlByPage(ndList, page.getCurrent(), page.getSize(), kcdm, kqbh, xzqhList, kqmc, tjdx);
        List<Map<String, Object>> list = hisiKsMapper.getzyclBhlCountByPage(ndList, kcdm, kqbh, xzqhList, kqmc, tjdx);
        long count = 0;
        if (CollectionUtil.isNotEmpty(list)) {
            count = Long.parseLong((String.valueOf(list.get(0).get("count"))));
        }
        page.setRecords(mapList);
        page.setTotal(count);
        result.put("page", page);

        //动态表头
        Map<String, String> titleMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(mapList)) {
            titleMap = getHeader(mapList.get(0));
        }
        result.put("header", titleMap);
        result.put("headers", getAsyncHead(numbersAsStrArray));
        return result;
    }

    /**
     * 查询统计导出-重构
     *
     * @param cxtjMhtj
     * @param response
     */
    @Override
    public void exportQueryStatistics(CxtjMhtj cxtjMhtj, MultipartFile file, HttpServletResponse response) {
        //处理导出excel的数据集合
        List<Map<String, Object>> listMap = new ArrayList<>();

        List<List<String>> dynamicHeader = new ArrayList<>();
        //中文字段
        List<String> chinanHeader = new ArrayList<>();
        //英文字段
        List<String> englishHeader = new ArrayList<>();
        Map maps = JSONUtil.toBean(cxtjMhtj.getDynamicHeader(), Map.class);
        // 使用keySet()方法获取所有键的集合
        Set keySet = maps.keySet();
        for (Object key : keySet) {
            englishHeader.add(key.toString());
            chinanHeader.add(maps.get(key).toString());
        }
        dynamicHeader.add(chinanHeader);//中文
        dynamicHeader.add(englishHeader);//英文
        cxtjMhtj.setSize(999999999);
        cxtjMhtj.setCurrent(1);
        String sheetName = "";
        //矿山，矿产地查询返回数据对象
        List<KsxxhzVo> ksxxhzVoList = new ArrayList<>();
        //导出模块类型（1：矿山信息查询，2：矿产地信息查询，3：矿产地规模统计，4资源储量查询）
        if (cxtjMhtj.getModuleType() == 1) {
            Page<KsxxhzVo> page = iKshzService.queryKshzPage(cxtjMhtj, file);
            ksxxhzVoList = page.getRecords();
            listMap = convertListToMaps(ksxxhzVoList);
            List<ExcelDataVo> excelDataVoList = new ArrayList<>();
            try {
                if (file != null) {
                    excelDataVoList = ExcelToReadUtil.excelRearer(file.getInputStream());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //excel上传时许可证号条件
            if (excelDataVoList.size() > 0) {
                // 提取 ksxxhzVoList 中的所有 xkzh 到一个 Set 中
                Set<String> ksxxhzXkzhSet = ksxxhzVoList.stream()
                        .map(KsxxhzVo::getXkzh)
                        .filter(StringUtils::isNotBlank) // 过滤掉空值
                        .collect(Collectors.toSet());

                // 筛选出 excelDataVoList 中与 ksxxhzXkzhSet 不匹配的记录
                List<KsxxhzVo> unmatchedExcelDataVoList = excelDataVoList.stream()
                        .filter(excelDataVo -> {
                            String xkzh = StringUtils.trimToEmpty(excelDataVo.getXkzh()); // 去除空格
                            return !ksxxhzXkzhSet.contains(xkzh);
                        })
                        .map(excelDataVo -> {
                            KsxxhzVo unmatchedExcelDataVo = new KsxxhzVo();
                            unmatchedExcelDataVo.setXkzh(excelDataVo.getXkzh());
                            return unmatchedExcelDataVo;
                        })
                        .collect(Collectors.toList());


                // 如果有未匹配的记录，则将其转换为 Map 并添加到 listMap
                if (unmatchedExcelDataVoList.size() > 0) {
                    List<Map<String, Object>> convertedMaps = convertListToMaps(unmatchedExcelDataVoList);
                    listMap.addAll(convertedMaps);
                }
            }


            sheetName = "矿权信息";
        } else if (cxtjMhtj.getModuleType() == 2) {
            Page<KsxxhzVo> page = iKshzService.queryKcdxxhzPage(cxtjMhtj);
            ksxxhzVoList = page.getRecords();
            listMap = convertListToMaps(ksxxhzVoList);
            sheetName = "矿产地信息";
        } else if (cxtjMhtj.getModuleType() == 3) {
        } else if (cxtjMhtj.getModuleType() == 4) {
            Page<ZyclVo> page = pageZyclVo(cxtjMhtj);
            List<ZyclVo> list = page.getRecords();
            listMap = convertListToMaps(list);
            sheetName = "资源储量";
        }

        try {
            ExcelExporter.exportZyclBhl(listMap, dynamicHeader, sheetName, response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 将任意类型的列表转换为 List<Map<String, Object>>，动态获取所有字段，包括继承的字段
     *
     * @param <T>  泛型类型
     * @param list 需要转换的列表
     * @return 转换后的 List<Map<String, Object>>
     */
    public <T> List<Map<String, Object>> convertListToMaps(List<T> list) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(list)) {
            mapList = list.stream()
                    .map(item -> {
                        Map<String, Object> map = new HashMap<>();
                        Class<?> clazz = item.getClass();
                        while (clazz != Object.class) {
                            for (Field field : clazz.getDeclaredFields()) {
                                field.setAccessible(true);
                                try {
                                    map.put(field.getName(), field.get(item));
                                } catch (IllegalAccessException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            clazz = clazz.getSuperclass();
                        }
                        return map;
                    })
                    .collect(Collectors.toList());
        }
        return mapList;
    }

    /**
     * 矿产地规模统计
     *
     * @param nd
     * @param kcdm
     * @author sqq
     * @since 2024/5/11 19:11
     */
    @Override
    public List<Kcdgmtj> getKcdgmtjList(Integer nd, String kcdm) {
        List<Kcdgmtj> kcdgmtjList = new ArrayList<>();
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        //省级用户
        // String xzqh = String.valueOf(user.getDirectorId());
        String xzqh = user.getOrgId();
        if (user.getOrgId().equals("0") || user.getOrgId().equals("-1")) {
            xzqh = "130000";
        }
        String sql = "";
        if (nd != null && nd > 0) {
            sql += " and nd=" + nd;
        }
        if (kcdm != null && !kcdm.equals("")) {
            List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
            if (kzbhList != null && kzbhList.size() == 3) {
                if (kzbhList.get(0) == 2) {
                    sql += " kcdm=" + kzbhList.get(1) + " and";
                } else if (kzbhList.get(0) == 3) {
                    sql += " kcdm='" + kzbhList.get(1) + "' and tjdx=" + kzbhList.get(2) + " and";
                }
            }

//            sql += " and kcdm='" + kcdm + "'";
        }

        QueryWrapper<Cb08Xzqh> xianWrapper = new QueryWrapper<>();
        xianWrapper.eq("dm", Integer.parseInt(xzqh));
        Cb08Xzqh sheng = cb08XzqhMapper.selectOne(xianWrapper);
        Kcdgmtj shengKcdgmtj = new Kcdgmtj();
        String shengdm = xzqh.replaceAll("0+$", "");
        sql += " and xzqdm like'%" + shengdm + "%'";
        shengKcdgmtj = hisiKsMapper.selectKcdgmtj(sql);
        if (shengKcdgmtj != null) {
            shengKcdgmtj.setXzqhdm(String.valueOf(sheng.getDm()));
            shengKcdgmtj.setXzqhmc(sheng.getMc());
            kcdgmtjList.add(shengKcdgmtj);
        }

        QueryWrapper<Cb08Xzqh> shiWrapper = new QueryWrapper<>();
        shiWrapper.eq("fdm", Integer.parseInt(xzqh));
        List<Cb08Xzqh> shiList = cb08XzqhMapper.selectList(shiWrapper);
        for (Cb08Xzqh shi : shiList) {
            String sqlshi = "";
            if (nd != null && nd > 0) {
                sqlshi += " and nd=" + nd;
            }
            if (kcdm != null && !kcdm.equals("")) {
//                sqlshi += " and kcdm='" + kcdm + "'";

                List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
                if (kzbhList != null && kzbhList.size() == 3) {
                    if (kzbhList.get(0) == 2) {
                        sqlshi += " kcdm=" + kzbhList.get(1) + " and";
                    } else if (kzbhList.get(0) == 3) {
                        sqlshi += " kcdm='" + kzbhList.get(1) + "' and tjdx=" + kzbhList.get(2) + " and";
                    }
                }

            }
            String shiDm = String.valueOf(shi.getDm()).replaceAll("0+$", "");
            sqlshi += " and xzqdm like'%" + shiDm + "%'";
            Kcdgmtj shiKcdgmtj = hisiKsMapper.selectKcdgmtj(sqlshi);
            if (shiKcdgmtj != null) {
                shiKcdgmtj.setXzqhdm(String.valueOf(shi.getDm()));
                shiKcdgmtj.setXzqhmc(shi.getMc());
                kcdgmtjList.add(shiKcdgmtj);
            }
        }
        return kcdgmtjList;
    }

    /**
     * 矿产地规模统计-重构
     *
     * @param nd
     * @param kcdm
     * @author Kevin
     * @since 2024/7/5 19:11
     */
    public List<KcdgmtjVo> getKcdgmtjListNew1(Integer nd, String kcdm) {
        List<KcdgmtjVo> kcdgmtjList = new ArrayList<>();

        if (kcdm == null) {
            return kcdgmtjList;
        }
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        //行政区代码
        int xzqh;
        if (user.getOrgId() != null) {
            if (user.getOrgId().equals("-1")) {
                xzqh = 130000;
            } else {
                xzqh = Integer.parseInt(user.getOrgId());
            }
        } else {
            xzqh = 130000;
        }

//        //河北省
//        QueryWrapper<Cb08Xzqh> shengWrapper = new QueryWrapper<>();
//        shengWrapper.eq("dm", xzqh);
//        Cb08Xzqh sheng = cb08XzqhMapper.selectOne(shengWrapper);

        KcdgmtjVo shengKcdgmtj = getKcdgmtjVo(nd, kcdm, xzqh);
        if (shengKcdgmtj != null) {
            kcdgmtjList.add(shengKcdgmtj);
        }

        QueryWrapper<Cb08Xzqh> shiWrapper = new QueryWrapper<>();
        shiWrapper.eq("fdm", xzqh);
        shiWrapper.orderByAsc("dm");
        List<Cb08Xzqh> shiList = cb08XzqhMapper.selectList(shiWrapper);
        if (CollectionUtil.isNotEmpty(shiList)) {
            for (Cb08Xzqh shi : shiList) {
                KcdgmtjVo shiKcdgmtj = getKcdgmtjVo(nd, kcdm, shi.getDm());
                if (shiKcdgmtj != null) {
                    kcdgmtjList.add(shiKcdgmtj);
                }
            }
        }

//        return hisiKsMapper.getKcdgmtjListNew(nd, kcdm);

        return kcdgmtjList;
    }

    /**
     * 矿产地规模统计-重构
     *
     * @param nd
     * @param kcdm
     * @author Kevin
     * @since 2024/7/5 19:11
     */
    @Override
    public List<KcdgmtjVo> getKcdgmtjListNew(Integer nd, String kcdm) {
        List<KcdgmtjVo> kcdgmtjList = new ArrayList<>();
        //查询年度附表6数据
        List<Map> maps = new ArrayList<>();
        if (kcdm == null) {
            return kcdgmtjList;
        }
        //获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        Role role = roleMapper.selectById(saBaseLoginUser.getPositionId());
        List<Map> xzqhList = new ArrayList<>();


        if (SysRoleEnum.ADMIN.getValue().equals(role.getCode()) || SysRoleEnum.BJSH.getValue().equals(role.getCode()) || SysRoleEnum.SHENGSH.getValue().equals(role.getCode())) {
            xzqhList = cb08XzqhMapper.getShengXzqhList(130000);
            maps = zyclSixMapper.getShiGm(nd);
        } else if (SysRoleEnum.SHISH.getValue().equals(role.getCode())) {
            Integer xkzh = Integer.valueOf(saBaseLoginUser.getDirectorId());
            xzqhList = cb08XzqhMapper.getShiXzqhList(xkzh);
            maps = zyclSixMapper.getGm(nd);
        } else if (SysRoleEnum.XIANSH.getValue().equals(role.getCode())) {
            Integer xkzh = Integer.valueOf(saBaseLoginUser.getDirectorId());
            xzqhList = cb08XzqhMapper.getXianXzqhList(xkzh);
            maps = zyclSixMapper.getGm(nd);

        }
        List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
        List<KcdgmtjVo> kcdmList = new ArrayList<>();
        NbfbSixVo nbfbSixVo = new NbfbSixVo();
        if (kzbhList != null && kzbhList.size() == 3) {
            LambdaQueryWrapper<Cb06Kc> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cb06Kc::getKcdm, kzbhList.get(1));
            wrapper.eq(Cb06Kc::getTjdx, kzbhList.get(2));
            Cb06Kc cb06Kc = cb06KcMapper.selectOne(wrapper);
            if (cb06Kc != null) {
                if (cb06Kc.getXsbs() == 0) {
                    nbfbSixVo.setDw(cb06Kc.getJsldw());
//                    nbfbSixVo.setKcmc(cb06Kc.getKcmc() + " (" + cb06Kc.getJsdxmc() + ")");
                } else if (cb06Kc.getXsbs() == 1) {
                    nbfbSixVo.setDw(cb06Kc.getKsldw());
//                    nbfbSixVo.setKcmc(cb06Kc.getKcmc());
                }
                if (cb06Kc.getJsdxmc() != null && !cb06Kc.getJsdxmc().equals("")) {
                    nbfbSixVo.setKcmc(cb06Kc.getKcmc() + " (" + cb06Kc.getJsdxmc() + ")");
                } else {
                    nbfbSixVo.setKcmc(cb06Kc.getKcmc());
                }


            }
        }
        kcdmList = new NbfbSixServiceImpl().getKcdgmtjListNew(xzqhList, kzbhList.get(1), kzbhList.get(2), maps, nbfbSixVo.getDw());

        if (kcdmList.size() > 0) {
            return kcdmList;
        }
        return kcdgmtjList;
    }

    /**
     * 循环拼接sql
     *
     * @param nd
     * @param kcdm
     * @param listMap
     * @return
     */
    public String getKqbhSql(Integer nd, String kcdm, List<Map> listMap) {
        String sql = "";
        if (nd != null) {
            sql += "zy.nd=" + nd + " and ";
        }

        List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
        if (kzbhList != null && kzbhList.size() == 3) {
            if (kzbhList.get(0) == 2) {
                sql += " zy.kcdm=" + kzbhList.get(1) + " and";
            } else if (kzbhList.get(0) == 3) {
                sql += " zy.kcdm='" + kzbhList.get(1) + "' and zy.tjdx=" + kzbhList.get(2) + " and";
            }
        }

        String kqbhSql = "";
        if (listMap.size() > 0) {
            kqbhSql = "  zy.kqbh in(";
            for (Map map : listMap) {
                String kqbh = String.valueOf(map.get("kqbh"));
                kqbhSql += "'" + kqbh + "',";
            }

            kqbhSql = kqbhSql.substring(0, kqbhSql.length() - 1) + ")";
        }


        return sql + kqbhSql;
    }


    public KcdgmtjVo getKcdgmtjVoOld(Integer nd, String kcdm, Integer xzqhdm) {
        //河北省
        KcdgmtjVo shengKcdgmtj = new KcdgmtjVo();
        QueryWrapper<Cb08Xzqh> shengWrapper = new QueryWrapper<>();
        shengWrapper.eq("dm", xzqhdm);
        Cb08Xzqh sheng = cb08XzqhMapper.selectOne(shengWrapper);
        String xzqh = String.valueOf(sheng.getDm()).replaceAll("0+$", "");

        String sql = " xzqdm like'" + xzqh + "%' and";

        if (nd != null) {
            sql += " nd=" + nd + " and";
        }


        List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
        if (kzbhList != null && kzbhList.size() == 3) {
            if (kzbhList.get(0) == 2) {
                sql += " kcdm=" + kzbhList.get(1) + " and";
            } else if (kzbhList.get(0) == 3) {
                sql += " kcdm='" + kzbhList.get(1) + "' and tjdx=" + kzbhList.get(2) + " and";
            }
        }


        //大型
        String bigGmSql = sql + "  gm='大型'";
        //中型
        String midGmSql = sql + "  gm='中型'";
        //小型
        String smallGmSql = sql + "  gm='小型'";
        List<Map> listbig = hisiKsMapper.getKqbhList(bigGmSql);
        List<Map> listmid = hisiKsMapper.getKqbhList(midGmSql);
        List<Map> listsmall = hisiKsMapper.getKqbhList(smallGmSql);
        shengKcdgmtj.setBigCount(listbig.size());
        shengKcdgmtj.setMediumCount(listmid.size());
        shengKcdgmtj.setSmallCount(listsmall.size());

        if (listbig.size() > 0) {
            Map mapbig = hisiKsMapper.selectzyl(getKqbhSql(nd, kcdm, listbig));
            if (mapbig != null) {
                shengKcdgmtj.setBigNmbyjsl(ToolData.roundToTwoDecimals((Double) mapbig.get("nmbyjsl")));
                shengKcdgmtj.setBigNmbyksl(ToolData.roundToTwoDecimals((Double) mapbig.get("nmbyksl")));
            }
        } else {
            shengKcdgmtj.setBigNmbyjsl(0.0);
            shengKcdgmtj.setBigNmbyksl(0.0);
        }

        if (listmid.size() > 0) {
            Map mapmid = hisiKsMapper.selectzyl(getKqbhSql(nd, kcdm, listmid));

            if (mapmid != null) {
                shengKcdgmtj.setMediumNmbyjsl(ToolData.roundToTwoDecimals((Double) mapmid.get("nmbyjsl")));
                shengKcdgmtj.setMediumNmbyksl(ToolData.roundToTwoDecimals((Double) mapmid.get("nmbyksl")));
            }
        } else {
            shengKcdgmtj.setMediumNmbyjsl(0.0);
            shengKcdgmtj.setMediumNmbyksl(0.0);
        }

        if (listsmall.size() > 0) {
            Map mapsmall = hisiKsMapper.selectzyl(getKqbhSql(nd, kcdm, listsmall));
            if (mapsmall != null) {
                shengKcdgmtj.setSmallNmbyjsl(ToolData.roundToTwoDecimals((Double) mapsmall.get("nmbyjsl")));
                shengKcdgmtj.setSmallNmbyksl(ToolData.roundToTwoDecimals((Double) mapsmall.get("nmbyksl")));
            }
        } else {
            shengKcdgmtj.setSmallNmbyjsl(0.0);
            shengKcdgmtj.setSmallNmbyksl(0.0);
        }

//        shengKcdgmtj.setXzqhdm(String.valueOf(sheng.getDm()));
        shengKcdgmtj.setXzqhmc(sheng.getMc());
        return shengKcdgmtj;
    }

    public KcdgmtjVo getKcdgmtjVo(Integer nd, String kcdm, Integer xzqhdm) {
        //河北省
        KcdgmtjVo shengKcdgmtj = new KcdgmtjVo();
        QueryWrapper<Cb08Xzqh> shengWrapper = new QueryWrapper<>();
        shengWrapper.eq("dm", xzqhdm);
        Cb08Xzqh sheng = cb08XzqhMapper.selectOne(shengWrapper);
        String xzqh = String.valueOf(sheng.getDm()).replaceAll("0+$", "");

        String sql = " CAST(k.xzqdm AS VARCHAR) like'" + xzqh + "%' and";

        if (nd != null) {
            sql += " k.nd=" + nd + " and";
        }


        List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
        if (kzbhList != null && kzbhList.size() == 3) {
            if (kzbhList.get(0) == 2) {
                sql += " zy.kcdm=" + kzbhList.get(1) + " and";
            } else if (kzbhList.get(0) == 3) {
                sql += " zy.kcdm='" + kzbhList.get(1) + "' and zy.tjdx=" + kzbhList.get(2) + " and";
            }
        }
//        sql += " zy.kcdm='" + kzbhList.get(0) + "' and zy.tjdx="+kzbhList.get(1) + " and";

        sql = sql.replaceFirst(" and$", "");

        //查询规模数据
        List<Map> list = hisiKsMapper.getGmtj(sql);
        if (list != null && list.size() > 0) {

            Map mapget0 = list.get(0);
            if (mapget0.get("kcmc") != null) {
                shengKcdgmtj.setKcmc(mapget0.get("kcmc").toString());
            }

            if (mapget0.get("jsdxmc") != null) {
                shengKcdgmtj.setJsdxmc(mapget0.get("jsdxmc").toString());
            }

            for (Map map : list) {
                if ("大型".equals(map.get("gmtype"))) {
                    if (map.get("gmcount") != null) {
                        shengKcdgmtj.setBigCount(Integer.valueOf(map.get("gmcount").toString()));
                        shengKcdgmtj.setBigNmbyjsl(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byjsl").toString())));
                        shengKcdgmtj.setBigNmbyksl(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byksl").toString())));
                        shengKcdgmtj.setBigNmby(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byl").toString())));
                    } else {
                        shengKcdgmtj.setBigNmbyjsl(0.0);
                        shengKcdgmtj.setBigNmbyksl(0.0);
                        shengKcdgmtj.setBigCount(0);
                        shengKcdgmtj.setBigNmby(0.0);
                    }

                }
                if ("中型".equals(map.get("gmtype"))) {
                    if (map.get("gmcount") != null) {
                        shengKcdgmtj.setMediumCount(Integer.valueOf(map.get("gmcount").toString()));
                        shengKcdgmtj.setMediumNmbyjsl(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byjsl").toString())));
                        shengKcdgmtj.setMediumNmbyksl(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byksl").toString())));
                        shengKcdgmtj.setMediumNmby(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byl").toString())));
                    } else {
                        shengKcdgmtj.setMediumNmbyjsl(0.0);
                        shengKcdgmtj.setMediumNmbyksl(0.0);
                        shengKcdgmtj.setMediumCount(0);
                        shengKcdgmtj.setMediumNmby(0.0);
                    }

                }
                if ("小型".equals(map.get("gmtype"))) {
                    if (map.get("gmcount") != null) {
                        shengKcdgmtj.setSmallCount(Integer.valueOf(map.get("gmcount").toString()));
                        shengKcdgmtj.setSmallNmbyjsl(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byjsl").toString())));
                        shengKcdgmtj.setSmallNmbyksl(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byksl").toString())));
                        shengKcdgmtj.setSmallNmby(ToolData.roundToTwoDecimals(Double.parseDouble(map.get("byl").toString())));
                    } else {
                        shengKcdgmtj.setSmallNmbyjsl(0.0);
                        shengKcdgmtj.setSmallNmbyksl(0.0);
                        shengKcdgmtj.setSmallCount(0);
                        shengKcdgmtj.setSmallNmby(0.0);
                    }
                }
//        shengKcdgmtj.setXzqhdm(String.valueOf(sheng.getDm()));
                shengKcdgmtj.setXzqhmc(sheng.getMc());

            }
            return shengKcdgmtj;
        } else {
            return null;
        }
    }


    @Override
    public Page<Zyclcx> pageZyclcx(CxtjMhtj cxtjMhtj) {
        DecimalFormat df = new DecimalFormat("#.00");
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        long current = cxtjMhtj.getCurrent();
        long size = cxtjMhtj.getSize();
        Page<Zyclcx> page = new Page<>(current, size);
        if (current < 1) {
            return page;
        }
        List<Zyclcx> zyclcxList = new ArrayList<>();
        //获取分页数据
        long count = (current - 1) * size;
        if (current == 1) {
            count = 0;
        }
        String sql = "";
        if (cxtjMhtj.getKqbh() != null && cxtjMhtj.getKqbh().length() > 0) {
            sql += " and kqbh like'%" + cxtjMhtj.getKqbh() + "%'";
        }
        if (cxtjMhtj.getKqmc() != null && cxtjMhtj.getKqmc().length() > 0) {
            sql += " and kqmc like'%" + cxtjMhtj.getKqmc() + "%'";
        }
        if (cxtjMhtj.getNd() != null && cxtjMhtj.getNd() > 0) {
            sql += " and nd=" + cxtjMhtj.getNd();
        }
        if (cxtjMhtj.getKzbh() != null && !cxtjMhtj.getKzbh().equals("")) {
            sql += " and kcdm='" + cxtjMhtj.getKzbh() + "'";
        }
        //行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null && cxtjMhtj.getXzqh().length() > 0) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .collect(Collectors.toList());
            String xzqhSql = "(";
            for (String xzqh : xzqhList) {
                xzqhSql += "'" + xzqh + "',";
            }
            xzqhSql = xzqhSql.substring(0, xzqhSql.length() - 1) + ")";

            sql += " and xzqdm in" + xzqhSql;
        } else {
            String xzqh = user.getOrgId();
            if (user.getOrgId().equals("0") || user.getOrgId().equals("-1")) {
                xzqh = "130000";
            }
            //  String xzqh = String.valueOf(user.getDirectorId());
            xzqh = xzqh.replaceAll("0+$", "");
            sql += " and xzqdm like'%" + xzqh + "%'";
        }

        sql = sql.substring(4);

        String sqlLimit = "select kqbh,kcdm,nd from hisi_ks where " + sql + " GROUP BY kqbh,kcdm,nd ORDER BY nd DESC,kqbh ASC LIMIT " + size + " OFFSET " + count;

        List<ZyclcxVo> zyclcxVoList = hisiKsMapper.selectKqbh(sqlLimit);
        for (ZyclcxVo zyclcx : zyclcxVoList) {
            Zyclcx zyclcx1 = new Zyclcx();
            // "证实量")
            Double zsl = 0.0;
            // "可信量")
            Double kxl = 0.0;
            // "证实可信合计")
            double zskxhjl = 0.0;
            // "探明量")
            Double tml = 0.0;
            // "控制量")
            Double kzl = 0.0;
            // "推断量")
            Double tdl = 0.0;
            // "探明，控制，推断合计量")
            Double tmkztdl = 0.0;
            QueryWrapper<HisiKs> zyclcxWrapper = new QueryWrapper<>();
            zyclcxWrapper.eq("kqbh", zyclcx.getKqbh());
            zyclcxWrapper.eq("kcdm", zyclcx.getKcdm());
            zyclcxWrapper.eq("nd", zyclcx.getNd());
            List<HisiKs> hisiKsList = hisiKsMapper.selectList(zyclcxWrapper);
            HisiKs hisiKsfist = hisiKsList.get(0);
            for (HisiKs hisiKs : hisiKsList) {
                if (hisiKs.getKqzsl() != null) {
                    zsl += hisiKs.getKqzsl();
                }
                if (hisiKs.getKqkxl() != null) {
                    kxl += hisiKs.getKqkxl();
                }
                if (hisiKs.getKqtml() != null) {
                    tml += hisiKs.getKqtml();
                }
                if (hisiKs.getKqkzl() != null) {
                    kzl += hisiKs.getKqkzl();
                }
                if (hisiKs.getKqtdl() != null) {
                    tdl += hisiKs.getKqtdl();
                }


            }
            zskxhjl = zsl + kxl;
            tmkztdl = tml + kzl + tdl;
            zyclcx1.setKqbh(hisiKsfist.getKqbh());//矿区编号
            zyclcx1.setKzdm(hisiKsfist.getKcdm());//矿产代码
            zyclcx1.setNd(hisiKsfist.getNd());//年度
            zyclcx1.setKzmc(hisiKsfist.getKcmc());//矿产名称
            zyclcx1.setKqmc(hisiKsfist.getKqmc());//矿区名称
            zyclcx1.setJsldw(hisiKsfist.getJsldw());//金属量单位
            zyclcx1.setKsldw(hisiKsfist.getKsldw());//矿石量单位
            zyclcx1.setZsl(Double.valueOf(df.format(zsl)));
            zyclcx1.setKxl(Double.valueOf(df.format(kxl)));
            zyclcx1.setZskxhjl(Double.valueOf(df.format(zskxhjl)));
            zyclcx1.setTml(Double.valueOf(df.format(tml)));
            zyclcx1.setKzl(Double.valueOf(df.format(kzl)));
            zyclcx1.setTdl(Double.valueOf(df.format(tdl)));
            zyclcx1.setTmkztdl(Double.valueOf(df.format(tmkztdl)));
            QueryWrapper<Cb08Xzqh> xianWrapper = new QueryWrapper<>();
            xianWrapper.eq("dm", Integer.parseInt(hisiKsfist.getXzqdm()));
            Cb08Xzqh xian = cb08XzqhMapper.selectOne(xianWrapper);

            QueryWrapper<Cb08Xzqh> shiWrapper = new QueryWrapper<>();
            shiWrapper.eq("dm", xian.getFdm());
            Cb08Xzqh shi = cb08XzqhMapper.selectOne(shiWrapper);

            QueryWrapper<Cb08Xzqh> shengWrapper = new QueryWrapper<>();
            shengWrapper.eq("dm", shi.getFdm());
            Cb08Xzqh sheng = cb08XzqhMapper.selectOne(shengWrapper);
            zyclcx1.setXzqhmc((sheng.getMc() + ">" + shi.getMc() + ">" + xian.getMc()));
            zyclcxList.add(zyclcx1);
        }


        System.out.println(sql);
        System.out.println(zyclcxVoList);


        page.setRecords(zyclcxList);
        List<ZyclcxVo> zyclcxVoListsize = hisiKsMapper.selectKqbh("select kqbh,kcdm,nd from hisi_ks where " + sql + " GROUP BY kqbh,kcdm,nd ORDER BY nd DESC");
        page.setTotal(zyclcxVoListsize.size());


        return page;
    }

    /**
     * 资源储量查询统计-重构
     *
     * @param param
     * @author Sqq
     * @since 2024/7/6 17:56
     */
    @Override
    public Page<ZyclVo> pageZyclVo(CxtjMhtj param) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        Page<ZyclVo> iPage = new Page<>();
        iPage.setCurrent(param.getCurrent());
        iPage.setSize(param.getSize());

        //行政区代码
        String xzqh =null;
        Integer kcdm=null;
        Integer tjdx=null;

        if (!StrUtil.isNotBlank(param.getXzqh())) {
            if (user.getOrgId() != null) {
                if (user.getOrgId().equals("-1")) {
                    xzqh = "130000";
                } else {
                    xzqh = user.getOrgId();
                }
            } else {
                xzqh = "130000";
            }

            xzqh = xzqh.replaceAll("0+$", "");
        }
        if (param.getKzbh() != null) {  //TypeProcessing.strToListComma()

            List<Integer> kzbhList = TypeProcessing.strToList(param.getKzbh());
            if (kzbhList != null && kzbhList.size() == 3) {
                if (kzbhList.get(0) == 2) {
                    kcdm=kzbhList.get(1);
                } else if (kzbhList.get(0) == 3) {
                    kcdm=kzbhList.get(1);
                    tjdx=kzbhList.get(2);
                }
            }
        }

    List<Integer> xzqhList =TypeProcessing.strToListComma(param.getXzqh());

        iPage=  hisiKsMapper.pageZyclVoNew(iPage,kcdm, tjdx, xzqh,param.getNd(),param.getKqmc(),param.getKqbh(),xzqhList );
        return iPage;
    }


    /**
     * 资源储量查询统计总量-重构
     *
     * @param param
     * @author sqq
     * @since 2024/7/30 17:57
     */
    @Override
    public ZyclCountVo getZyclTotal(CxtjMhtj param) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        Page<ZyclVo> iPage = new Page<>();
        iPage.setCurrent(param.getCurrent());
        iPage.setSize(param.getSize());

        //行政区代码
        String xzqh =null;
        Integer kcdm=null;
        Integer tjdx=null;

        if (!StrUtil.isNotBlank(param.getXzqh())) {
            if (user.getOrgId() != null) {
                if (user.getOrgId().equals("-1")) {
                    xzqh = "130000";
                } else {
                    xzqh = user.getOrgId();
                }
            } else {
                xzqh = "130000";
            }

            xzqh = xzqh.replaceAll("0+$", "");
        }
        if (param.getKzbh() != null) {  //TypeProcessing.strToListComma()

            List<Integer> kzbhList = TypeProcessing.strToList(param.getKzbh());
            if (kzbhList != null && kzbhList.size() == 3) {
                if (kzbhList.get(0) == 2) {
                    kcdm=kzbhList.get(1);
                } else if (kzbhList.get(0) == 3) {
                    kcdm=kzbhList.get(1);
                    tjdx=kzbhList.get(2);
                }
            }
        }

        List<Integer> xzqhList =TypeProcessing.strToListComma(param.getXzqh());
        return hisiKsMapper.getZyclTotalNew(kcdm, tjdx, xzqh,param.getNd(),param.getKqmc(),param.getKqbh(),xzqhList);
    }

    /**
     * 查询统计数据导出
     *
     * @Param cxtjMhtj 筛选条件对象
     */
    @Override
    public void exportQuery(CxtjMhtj cxtjMhtj, HttpServletResponse response) {
        List<List<String>> dynamicHeader = new ArrayList<>();
        //中文字段
        List<String> chinanHeader = new ArrayList<>();
        //英文字段
        List<String> englishHeader = new ArrayList<>();
//        String time = DateUtil.format(new Date(), "YYYY-MM-dd");
//        String path=PathUtils.getUpLoadPath() + File.separator + time+".xlsx";
        Map maps = JSONUtil.toBean(cxtjMhtj.getDynamicHeader(), Map.class);
        // 使用keySet()方法获取所有键的集合
        Set keySet = maps.keySet();
        for (Object key : keySet) {
            englishHeader.add(key.toString());
            chinanHeader.add(maps.get(key).toString());
        }
        dynamicHeader.add(chinanHeader);//中文
        dynamicHeader.add(englishHeader);//英文
        cxtjMhtj.setSize(999999999);
        cxtjMhtj.setCurrent(1);

        //导出模块类型（1：矿山信息查询，2：矿产地信息查询，3：矿产地规模统计，4资源储量查询）
        if (cxtjMhtj.getModuleType() == 1 || cxtjMhtj.getModuleType() == 2) {
            Page<Ksxicx> page = pageHisiKs(cxtjMhtj);
            KsxxhzVo ksxxhzVo = new KsxxhzVo();
            List<Ksxicx> list = page.getRecords();
            try {
                ExcelExporter.exportKsandKcd(list, dynamicHeader, response, cxtjMhtj.getModuleType());
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        if (cxtjMhtj.getModuleType()==3){
//            List<Kcdgmtj> list= getKcdgmtjList(cxtjMhtj.getNd(), String.valueOf(cxtjMhtj.getKzbh()));
//            try {
//                ExcelExporter.exportKcdGm(list,dynamicHeader,response);
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        if (cxtjMhtj.getModuleType() == 4) {
            Page<Zyclcx> pageZyclcx = pageZyclcx(cxtjMhtj);
            List<Zyclcx> list = pageZyclcx.getRecords();
            try {
                ExcelExporter.exportZyclcx(list, dynamicHeader, response);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 矿产地分布 根据年度和矿区编号
     *
     * @param nd
     * @param xzqh
     * @return
     */

    @Override
    public List<Kcfb> getkcfbList(Integer nd, String xzqh) {
//        String[] kcdms = {"22001", "11001", "42201", "32017", "63941", "83906"};
//        List<String> kcdmList = Arrays.asList(kcdms);
//        List<Kcfb> kcfbList = new ArrayList<>();
//        for (String kcdm : kcdmList) {
//            Kcfb kcfb = new Kcfb();
//            List<Cb06Kc> cb06KcList = cb06KcMapper.selectList(new QueryWrapper<Cb06Kc>().eq("kcdm", Integer.valueOf(kcdm)));
//            Cb06Kc cb06Kc = cb06KcList.get(0);
//            kcfb.setKcdm(kcdm);
//            kcfb.setKcmc(cb06Kc.getKcmc());
//            kcfb.setKctbdw(cb06Kc.getTbdw());
////          if (cb06Kc.getTbtzxs().contains("e")||cb06Kc.getTbtzxs().contains("E")){
//            kcfb.setDwjz(Double.parseDouble(cb06Kc.getTbtzxs()));
////          }else{
////              kcfb.setDwjz(Double.parseDouble(cb06Kc.getTbtzxs()));
////          }
//            if (cb06Kc.getJsldw() != null && !cb06Kc.getJsldw().equals("")) {
//                kcfb.setKctjdw(cb06Kc.getJsldw());
//            } else {
//                kcfb.setKctjdw(cb06Kc.getKsldw());
//            }
//            List<Dykcfb> dykcfbList = new ArrayList<>();
//            List<Cb08Xzqh> cb08XzqhList = cb08XzqhMapper.selectList(new QueryWrapper<Cb08Xzqh>().eq("fdm", Integer.valueOf(xzqh)));
//            for (Cb08Xzqh cb08Xzqh : cb08XzqhList) {
//                String shixzqh = String.valueOf(cb08Xzqh.getDm()).replaceAll("0+$", "");
//                String sql = "and kcdm='" + cb06Kc.getKcdm() + "' and xzqdm like'%" + shixzqh + "%' and nd=" + nd;
//                Dykcfb dykcfb = hisiKsMapper.getDykcfb(sql);
//                dykcfb.setZyltj(BigDecimal.valueOf(dykcfb.getZyltj() * Double.parseDouble(cb06Kc.getTbtzxs())).setScale(2, RoundingMode.HALF_UP).doubleValue());
//                dykcfb.setXzqhmc(cb08Xzqh.getMc());
//                dykcfb.setXzqhdm(String.valueOf(cb08Xzqh.getDm()));
//                dykcfbList.add(dykcfb);
//            }
//            kcfb.setDykcfbList(dykcfbList);
//            kcfbList.add(kcfb);
//        }
//        return kcfbList;

        List<Kcfb> kcfbList = new ArrayList<>();
        //首先从redis中获取数据，若没有则从pg库中获取
        Object cacheValue = commonCacheOperator.get("kcfb" + nd);
        if (ObjectUtil.isNotEmpty(cacheValue)) {
            kcfbList = JSONUtil.toList(String.valueOf(cacheValue), Kcfb.class);
        } else {
            kcfbList = getkcfbListXian(nd, xzqh);
            commonCacheOperator.put("kcfb" + nd, JSONUtil.toJsonStr(kcfbList));
        }
        return kcfbList;
    }


    /**
     * 县行政区划矿产分布
     *
     * @param nd
     * @param xzqh
     * @return
     */
    public List<Kcfb> getkcfbListXian(Integer nd, String xzqh) {
        String[] kcdms = {"22001", "11001", "42201", "32017", "63941", "83906"};
        List<String> kcdmList = Arrays.asList(kcdms);
        List<Kcfb> kcfbList = new ArrayList<>();
        for (String kcdm : kcdmList) {
            Kcfb kcfb = new Kcfb();
            List<Cb06Kc> cb06KcList = cb06KcMapper.selectList(new QueryWrapper<Cb06Kc>().eq("kcdm", Integer.valueOf(kcdm)));
            Cb06Kc cb06Kc = cb06KcList.get(0);
            kcfb.setKcdm(kcdm);
            kcfb.setKcmc(cb06Kc.getKcmc());
            kcfb.setKctbdw(cb06Kc.getTbdw());
//          if (cb06Kc.getTbtzxs().contains("e")||cb06Kc.getTbtzxs().contains("E")){
            kcfb.setDwjz(Double.parseDouble(cb06Kc.getTbtzxs()));
//          }else{
//              kcfb.setDwjz(Double.parseDouble(cb06Kc.getTbtzxs()));
//          }
            if (cb06Kc.getJsldw() != null && !cb06Kc.getJsldw().equals("")) {
                kcfb.setKctjdw(cb06Kc.getJsldw());
            } else {
                kcfb.setKctjdw(cb06Kc.getKsldw());
            }
            List<Dykcfb> dykcfbList = new ArrayList<>();
            List<Cb08Xzqh> cb08XzqhList = cb08XzqhMapper.selectList(new QueryWrapper<Cb08Xzqh>().eq("fdm", Integer.valueOf(xzqh)));
            for (Cb08Xzqh cb08Xzqh : cb08XzqhList) {

                List<Cb08Xzqh> cb08XzqhxianList = cb08XzqhMapper.selectList(new QueryWrapper<Cb08Xzqh>().eq("fdm", cb08Xzqh.getDm()));
                //String shixzqh = String.valueOf(cb08Xzqh.getDm()).replaceAll("0+$", "");
                // String sql = "and kcdm='" + cb06Kc.getKcdm() + "' and xzqdm like'%" + shixzqh + "%' and nd=" + nd;

                for (Cb08Xzqh cb08Xzqhxian : cb08XzqhxianList) {
                    if (!cb08Xzqhxian.getMc().equals("市辖区")) {
                        String sql = "and kcdm='" + cb06Kc.getKcdm() + "' and xzqdm ='" + cb08Xzqhxian.getDm() + "' and nd=" + nd;
                        Dykcfb dykcfb = hisiKsMapper.getDykcfb(sql);
                        dykcfb.setZyltj(BigDecimal.valueOf(dykcfb.getZyltj() * Double.parseDouble(cb06Kc.getTbtzxs())).setScale(2, RoundingMode.HALF_UP).doubleValue());
//                    dykcfb.setXzqhmc(cb08Xzqh.getMc());
//                    dykcfb.setXzqhdm(String.valueOf(cb08Xzqh.getDm()));
                        if (dykcfb.getKcsl() > 0) {
                            dykcfb.setXzqhmc(cb08Xzqhxian.getMc());
                            dykcfb.setXzqhdm(String.valueOf(cb08Xzqhxian.getDm()));
                            dykcfbList.add(dykcfb);
                        }

                    }

                }


            }

//            LambdaQueryWrapper<Ks> ksQueryWrapper = new LambdaQueryWrapper<>();
//            ksQueryWrapper.eq(Ks::getZkcm, cb06Kc.getKcdm());
//            ksQueryWrapper.eq(Ks::getNd, nd);
//            List<Ks> ksList = ksMapper.selectList(ksQueryWrapper);
//            for (Ks ks : ksList){
//                if (ks.getZxdxzb() != null && ks.getZxdyzb() != null) {
//                    DecimalFormat df = new DecimalFormat("#.##########");
//                    Point point =transFormUtil.ConvertCoordinates4490(df.format(ks.getZxdxzb()), df.format(ks.getZxdyzb()));
//                    if (point != null) {
//                        ks.setZxdxzb(point.getX());
//                        ks.setZxdyzb(point.getY());
//                    }
//                }
//            }
//            kcfb.setKzdwfbList(ksList);
            kcfb.setDykcfbList(dykcfbList);
            kcfbList.add(kcfb);
        }
        return kcfbList;
    }


    @Override
    public Boolean updateKsData(Integer nd, String xzqhbm) {
//        QueryWrapper<HisiKs> queryWrapper = new QueryWrapper<>();
//        xzqhbm = xzqhbm.replaceAll("0+$", "");
//        queryWrapper.like("xzqh", xzqhbm);
//        queryWrapper.eq("nd", nd);
//        List<HisiKs> repetitionData = hisiKsMapper.selectList(queryWrapper);
//        if (repetitionData!=null&&repetitionData.size() > 0) {
//            //查询到历史数据反悔true
//            return true;
//        }else{
//            List<HisiKs> hisiKsList = hisiKsMapper.getupdateKsData(nd,xzqhbm);
//            for (HisiKs hisiKs : hisiKsList){
//                //添加规模
//                if (hisiKs.getKqbh()!=null){
//                    String gm=hisiKsMapper.getGm(nd,hisiKs.getKqbh(),Integer.valueOf(hisiKs.getKcdm()) , hisiKs.getTjdx(),Integer.valueOf(hisiKs.getDjflbh()));
//                    if (gm!=null){
//                        hisiKs.setGm(gm);
//                    }
//                    System.out.println(hisiKs.toString());
//
//
//
//                }
//            }
//        }

        List<HisiKs> hisiKsList = hisiKsMapper.getupdateKsData(nd, xzqhbm);
        for (HisiKs hisiKs : hisiKsList) {
            if (hisiKs.getKqbh() != null) {
                //添加规模
                String gm = hisiKsMapper.getGm(nd, hisiKs.getKqbh(), Integer.valueOf(hisiKs.getKcdm()), hisiKs.getTjdx(), Integer.valueOf(hisiKs.getDjflbh()));
                if (gm != null) {
                    hisiKs.setGm(gm);
                }
                //添加勘察阶段
                if (hisiKs.getDjflbh() != null) {
                    QueryWrapper<Bg> queryWrapperBg = new QueryWrapper<>();
                    queryWrapperBg.eq("kqbh", hisiKs.getKqbh());
                    queryWrapperBg.eq("djflbh", Integer.valueOf(hisiKs.getDjflbh()));
                    queryWrapperBg.eq("nd", nd);
                    queryWrapperBg.orderByDesc("bgtjrq");
                    queryWrapperBg.last("LIMIT 1");
                    Bg bg = bgMapper.selectOne(queryWrapperBg);
                    if (bg != null) {
                        hisiKs.setKcjdm(bg.getKcjdm());
                        hisiKs.setKcjdmc(bg.getKcjd());
                    }

                }
            }
            //添加开采情况(0未开采，1开采)
            if (hisiKs.getKqkcl() != null) {
                if (hisiKs.getKqkcl() > 0) {
                    hisiKs.setKcqk(1);
                } else {
                    hisiKs.setKcqk(0);
                }
            }
            //添加是否利用（0未利用，1利用）
            if (hisiKs.getKsbyl() != null) {
                if (hisiKs.getKsljl() != null) {
                    if (!hisiKs.getKsbyl().equals(hisiKs.getKsljl())) {
                        hisiKs.setSfly(1);
                    } else {
                        QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
                        queryWrapperKs.eq("kqbh", hisiKs.getKqbh());
                        queryWrapperKs.eq("nd", nd);
                        List<Ks> ksList = ksMapper.selectList(queryWrapperKs);
                        if (ksList.size() > 1) {
                            hisiKs.setSfly(1);
                        } else {
                            hisiKs.setSfly(0);
                        }
                    }
                }
            } else {
                hisiKs.setSfly(0);
            }


            //添加是否出界
            QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
            queryWrapperKs.eq("kqbh", hisiKs.getKqbh());
            queryWrapperKs.eq("djflbh", Integer.valueOf(hisiKs.getDjflbh()));
            queryWrapperKs.eq("nd", nd);
            Ks ks = ksMapper.selectOne(queryWrapperKs);
            boolean isInPolygon = getsfcj(ks);
            if (isInPolygon) {
                hisiKs.setSfcj(0);
            } else {
                hisiKs.setSfcj(1);
            }

            //矿产组合
            QueryWrapper<Cb01Zh> queryWrapperZh = new QueryWrapper<>();
            queryWrapperZh.eq("bnm", hisiKs.getKczhm());
            queryWrapperZh.eq("bh", 16);
            Cb01Zh cb01Zh = cb01ZhMapper.selectOne(queryWrapperZh);
            if (cb01Zh != null) {
                hisiKs.setZczh(cb01Zh.getMc());
            }
            System.out.println(hisiKs.toString());
            hisiKsMapper.insert(hisiKs);

        }


//
//            //添加是否出界
//            QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
//            queryWrapperKs.eq("kqbh","130107721" );
//            queryWrapperKs.eq("djflbh",1000);
//            queryWrapperKs.eq("nd", nd);
//            Ks ks = ksMapper.selectOne(queryWrapperKs);
//            boolean isInPolygon = getsfcj(ks);
//            if (isInPolygon) {
//                System.out.println("未出界");
//            } else {
//                System.out.println("出界");
//            }


        return null;
    }

    /**
     * 获取中心点坐标是否出界
     *
     * @param ks 矿山信息
     */
    public Boolean getsfcj(Ks ks) {
        try {
            if (ks != null) {
                QueryWrapper<Zb> queryWrapperZb = new QueryWrapper<>();
                queryWrapperZb.eq("kqbh", ks.getKqbh()).eq("djflbh", ks.getDjflbh()).eq("nd", ks.getNd());
                Zb zb = zbMapper.selectOne(queryWrapperZb);
                if (zb != null && zb.getKqzb() != null) {
                    System.out.println("坐标范围：" + zb.getKqzb());
                    return transFormUtil.isPointInPolygon(ks.getZxdxzb(), ks.getZxdyzb(), zb.getKqzb());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    @Override
    public void exportQueryKcfb(Integer nd, HttpServletResponse response) {
        List<List<String>> dynamicHeader = new ArrayList<>();
        List<Kcfb> kcfbList = getkcfbList(nd, "130000");
        List<Dcexcelkccb> dcexcelkccbs = new ArrayList<>();
        for (Kcfb kcfb : kcfbList) {

            List<Dykcfb> dykcfbList = kcfb.getDykcfbList();

            for (Dykcfb dykcfb : dykcfbList) {
                Dcexcelkccb dcexcelkccb = new Dcexcelkccb();
                BeanUtil.copyProperties(kcfb, dcexcelkccb);
                BeanUtil.copyProperties(dykcfb, dcexcelkccb);
                dcexcelkccbs.add(dcexcelkccb);
            }


        }
        //中文字段
        List<String> chinanHeader = new ArrayList<>();
        chinanHeader.add("矿种名称");
        chinanHeader.add("矿产代码");
        chinanHeader.add("矿产统计单位");
        chinanHeader.add("矿产通报单位");
        chinanHeader.add("单位进制");
        chinanHeader.add("行政区划代码");
        chinanHeader.add("行政区划名称");
        chinanHeader.add("矿产数量");
        chinanHeader.add("资源储量");
        //英文字段
        List<String> englishHeader = new ArrayList<>();
        englishHeader.add("kcmc");
        englishHeader.add("kcdm");
        englishHeader.add("kctjdw");
        englishHeader.add("kctbdw");
        englishHeader.add("dwjz");
        englishHeader.add("xzqhdm");
        englishHeader.add("xzqhmc");
        englishHeader.add("kcsl");
        englishHeader.add("zyltj");
        dynamicHeader.add(chinanHeader);//中文
        dynamicHeader.add(englishHeader);//英文
        try {
            ExcelExporter.exportZyclcx2(dcexcelkccbs, dynamicHeader, response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 多年年初年末保有量的变化量-导出Excel
     */
    @Override
    public void exportZyclBhl(ZyclBhlParam param, HttpServletResponse response) {


        String[] numbersAsStrArray = param.getNd().replace("，", ",").split(",");
        //参数转换为List<Integer>
        List<Integer> ndList = Arrays.stream(numbersAsStrArray)
                .map(Integer::parseInt)
                .sorted()
                .collect(Collectors.toList());

        //矿区编号
        String kqbh = "";
        //行政区代码
        List<Integer> xzqhList = new ArrayList<>();
        //矿产代码
        Integer kcdm = 0;
        //统计对象
        Integer tjdx = 0;
        //矿区名称
        String kqmc = "";
        if (param.getKcdm() != null) {
            List<Integer> kzbhList = TypeProcessing.strToList(param.getKcdm());
            if (kzbhList != null && kzbhList.size() == 3) {
                if (kzbhList.get(0) == 2) {
                    kcdm = kzbhList.get(1);
                } else if (kzbhList.get(0) == 3) {
                    kcdm = kzbhList.get(1);
                    tjdx = kzbhList.get(2);
                }
            }
        }
        if (param.getKqbh() != null) {
            kqbh = param.getKqbh();
        }
        if (param.getXzqh() != null) {
            //参数转换为List<Integer>
            xzqhList = Arrays.stream(param.getXzqh().replace("，", ",").split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        } else {
            //根据用户权限获取行政区信息
            xzqhList = getXzqhbh();

        }
        if (param.getKqmc() != null) {
            kqmc = param.getKqmc();
        }

//        List<Map<String, Object>> mapList = hisiKsMapper.getzyclBhlList(ndList);
        List<Map<String, Object>> mapList = hisiKsMapper.getzyclBhlList(ndList, kcdm, kqbh, xzqhList, kqmc, tjdx);

        //表头
        List<List<String>> headerList = new ArrayList<>();
        //中文字段 "统计对象",
        List<String> chineseHeader = new ArrayList<>(Arrays.asList(new String[]{"市名称", "县名称", "矿种名称", "统计对象名称", "金属量单位", "矿石量单位"}));
        //英文字段 "tjdx",
        List<String> englishHeader = new ArrayList<>(Arrays.asList(new String[]{"smc", "xmc", "kcmc", "jsdxmc", "jsldw", "ksldw",}));
        if (CollectionUtil.isNotEmpty(mapList)) {

            for (Integer year : ndList) {
                chineseHeader.add(year + "年初保有量");
                chineseHeader.add(year + "变化量");
                chineseHeader.add(year + "年末保有量");

                englishHeader.add("ncbyl" + year);
                englishHeader.add("bhl" + year);
                englishHeader.add("nmbyl" + year);
            }

            headerList.add(chineseHeader);
            headerList.add(englishHeader);
        }
        try {
            ExcelExporter.exportZyclBhl(mapList, headerList, "年初年末保有量变化量", response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据当前用户获取他所在行政区以及获取他下级行政区划
     *
     * @return List<Integer>
     * @Author: sqq
     */
    public List<Integer> getXzqhbh() {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        List<Integer> xzqhbhList = new ArrayList<>();
        //行政区代码
        String xzqh = "";
        if (user.getOrgId() != null) {
            if (user.getOrgId().equals("-1")) {
                xzqh = "130000";
            } else {
                xzqh = user.getOrgId();
            }
        } else {
            xzqh = "130000";
        }
//        QueryWrapper<Cb08Xzqh> fxzqWrapper = new QueryWrapper<>();
//        fxzqWrapper.eq("dm", Integer.valueOf(xzqh));
//        Cb08Xzqh cb08Xzqh=cb08XzqhMapper.selectOne(fxzqWrapper);
//        if (cb08Xzqh!=null){
//            xzqhbhList.add(cb08Xzqh.getDm());
//        }
        QueryWrapper<Cb08Xzqh> shiWrapper = new QueryWrapper<>();
        shiWrapper.eq("fdm", Integer.valueOf(xzqh));
        shiWrapper.orderByAsc("dm");
        List<Cb08Xzqh> shiList = cb08XzqhMapper.selectList(shiWrapper);
        if (CollectionUtil.isNotEmpty(shiList)) {
            for (Cb08Xzqh shi : shiList) {
                xzqhbhList.add(shi.getDm());
            }
        }


        QueryWrapper<Cb08Xzqh> xianWrapper = new QueryWrapper<>();
        xianWrapper.in("fdm", xzqhbhList);
        xianWrapper.orderByAsc("dm");
        List<Cb08Xzqh> xianList = cb08XzqhMapper.selectList(xianWrapper);
        List<Integer> xzqhbhs = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(xianList)) {
            for (Cb08Xzqh xian : xianList) {
                xzqhbhs.add(xian.getDm());
            }
        }


        return xzqhbhs;
    }

    /**
     * 临时规模导出所有矿种的导出Excel
     */
    @Override
    public void exportAllKcGmExcel(NbfbSixParam param, HttpServletResponse response) {
        List<KcdgmtjVo> list = new ArrayList<>();
        String kcdmStr = param.getKcdm();
        List<String> listKcdm = Arrays.asList(kcdmStr.split(","));

        for (String s : listKcdm) {
            List<KcdgmtjVo> everyList = getKcdgmtjListNew(param.getNd(), s);
            list.addAll(everyList);
        }
        String[] zw = new String[]{"行政区代码", "行政区名称", "矿种名称", "计算对象名称", "大型矿地", "大型矿保有", "中型矿地", "中型矿保有量", "小型矿地", "小型矿保有量"};
        String[] yw = new String[]{"xzqhdm", "xzqhmc", "kcmc", "jsdxmc", "bigCount", "bigNmby", "mediumCount", "mediumNmby", "smallCount", "smallNmby"};
        List<List<String>> dynamicHeader = new ArrayList<>();
        //中文字段
        List<String> chinanHeader = Arrays.asList(zw);
        //英文字段
        List<String> englishHeader = Arrays.asList(yw);
        dynamicHeader.add(chinanHeader);//中文
        dynamicHeader.add(englishHeader);//英文
        try {
            ExcelExporter.exportKcdGm(list, dynamicHeader, response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
